package com.helloandroid.models.butie

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.app.model.AppCache
import com.helloandroid.ext.parseBsInfo
import com.helloandroid.ext.process
import com.helloandroid.tools.Http.asyncHttpReq
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.NetWorkUtil
import com.helloandroid.vo.BsInfo
import kotlinx.coroutines.*
import org.json.JSONObject

class BsViewModel : ViewModel() {

    fun getInfo(callback:(Boolean,BsInfo?)->Unit){

        val info = AppCache.copyBsInfo()
        if (info != null){
            info.bs = AppUtil.user.bs
            callback(true,info)
            return
        }

        if(!NetWorkUtil.networkConnected()){
            AppUtil.toast("请打卡网络.")
            callback(false,info)
            return
        }

        viewModelScope.launch {
            val user = AppUtil.user
            val url = "butie/bushu/info?user_id=${user.user_id}&sys_bushu=${user.bs_sys}&time=${AppUtil.sysTime}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseBsInfo)
            if (parseResult.err == 0){
                val bsInfo = parseResult.obj as BsInfo
                user.bs = bsInfo.bs // 同步一次步数
                AppCache.bsInfo = bsInfo
                callback(true,AppCache.copyBsInfo())
            }else{
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
                callback(false,null)
            }
        }
    }

    fun perSecondTick(action:()->Unit){
        viewModelScope.launch {
            launch(Dispatchers.Default){
                while (isActive){
                    delay(1000L)
                    withContext(Dispatchers.Main){
                        action()
                    }
                }
            }
        }
    }

//    fun award(){
//        if(!NetWorkUtil.networkConnected()){
//            AppUtil.toast("请打卡网络.")
//            return
//        }
//        viewModelScope.launch {
//            val url = "butie/bushu/daka?user_id=${MyApplication.user!!.user_id}"
//            val jsonObj = JSONObject(asyncHttpReq(url))
//            val parseResult = jsonObj.process(JSONObject::parseCoinResponse)
//
//            if (parseResult.err == 0){
//                val coinResponse = parseResult.obj as CoinResponse
//                AppUtil.toast(" 恭喜获得奖励 ${coinResponse.added} 金币!")
//                MyApplication.setCoin(coinResponse.total)
//                val info = bsInfo.value!!
//                info.state = 1
//                bsInfo.value = info
//
//                // 存一个领取时间,用于通知判断
//                MyApplication.saveNotifyThings(AppConfig.KeyBSAwardTimeMs,MyApplication.sysTime)
//            }else{
//                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
//            }
//        }
//    }
}